package mysql

import (
	"goods/goodsrpc/goodsrpc"
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	Name    string  `gorm:"type:varchar(30);not null;comment:商品名称"`
	Price   float64 `gorm:"type:decimal(10,2);not null;comment:商品价格"`
	Stock   int64   `gorm:"type:int(11);not null;comment:商品库存"`
	Image   string  `gorm:"type:varchar(255);not null;comment:商品图片"`
	ClassId int64   `gorm:"type:int(11);not null;comment:分类id"`
}

func (g *Goods) GoodsAdd(db *gorm.DB) error {
	return db.Debug().Create(g).Error
}

func (g *Goods) FindGoodsByName(db *gorm.DB, name string) error {
	return db.Debug().Where("name=?", name).First(g).Error
}

/*
SELECT

	goods.`name` goodsName,
	goods.price,
	goods.stock,
	goods.image,
	classes.`name` className

FROM

	goods
	JOIN classes ON goods.class_id = classes.id
*/
func GoodsList(db *gorm.DB) []*goodsrpc.GoodsList {
	var list []*goodsrpc.GoodsList
	db.Debug().Model(&Goods{}).
		Select(
			"goods.`name` goods_name",
			"goods.price",
			"goods.stock",
			"goods.image",
			"classes.`name` class_name",
			"goods.id goods_id",
			"goods.created_at create_at",
		).
		Joins("left join classes ON goods.class_id = classes.id").
		Find(&list)
	return list
}
